const express = require("express");
const router = express.Router();
const user = require("../model/user");
const articel = require("../model/article");
const log = require("../model/log");
const category=require("../model/category");





module.exports = function (req, res) {
    var obj = {}
    articel.find().count().then((count) => {
        obj.count=count;
        let page = req.params.page;
        let limit = 8;
        let maxpage = Math.ceil(count / limit);
        page = Math.min(page, maxpage);
        page = Math.max(1, page);
        let skip = (page - 1) * limit;
        obj.page=page;
        obj.maxpage=maxpage;

        return articel.find().sort({ views: -1 }).limit(limit).skip(skip).populate("author");

    }).then(art => {
        obj.art=art;
        return articel.find().sort({ date: -1 }).limit(5);

    }).then(lart => {
        obj.lart=lart;
        return log.find().sort({ date: -1 }).limit(5)

    }).then(logcont => {
        obj.logcont=logcont;
        return user.findOne({ "userName": "ym深" })

    }).then(admin => {
        obj.admin=admin;
        return category.find();
    }).then(catearray=>{
        if (req.session.ifLogin) {
            user.findOne({ _id: req.session.user._id }).then(result => {
                res.render("index", {
                    iflogin: req.session.ifLogin,
                    user: result,
                    articel: obj.art,
                    page:obj.page,
                    maxpage:obj.maxpage,
                    logcont:obj.logcont,
                    lart:obj.lart,
                    admin:obj.admin,
                    count:obj.count,
                    catearray
                });
            })
        } else {
            res.render("index", {
                iflogin: req.session.ifLogin,
                // user:req.session.user,
                articel: obj.art,
                page:obj.page,
                maxpage:obj.maxpage,
                logcont:obj.logcont,
                lart:obj.lart,
                admin:obj.admin,
                count:obj.count,
                catearray
            });
        }
    })
};

